import React, { useState, useEffect } from 'react';
import { Outlet, useNavigate, useLocation } from 'react-router-dom';
import {
  Layout,
  Menu,
  Button,
  theme,
  Dropdown,
  Space,
  Avatar,
  message
} from 'antd';
import {
  ShoppingOutlined,
  AppstoreOutlined,
  ShoppingCartOutlined,
  UserOutlined,
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  DashboardOutlined,
  DownOutlined,
  LogoutOutlined,
} from '@ant-design/icons';
import { getUserAvatarPlaceholder } from '../utils/imageUtils';

const { Header, Sider, Content, Footer } = Layout;

// 后台布局组件
const AdminLayout = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const [collapsed, setCollapsed] = useState(false);
  const [selectedKeys, setSelectedKeys] = useState(['/admin/dashboard']);
  const [user, setUser] = useState(null);

  const {
    token: { colorBgContainer, borderRadiusLG },
  } = theme.useToken();

  // 检查用户是否登录
  useEffect(() => {
    const userInfo = localStorage.getItem('adminUser');
    if (!userInfo) {
      navigate('/admin/login');
      return;
    }

    try {
      const parsedUser = JSON.parse(userInfo);
      setUser(parsedUser);
    } catch (error) {
      console.error('解析用户信息失败', error);
      navigate('/admin/login');
    }
  }, [navigate]);

  // 更新选中的菜单项
  useEffect(() => {
    const path = location.pathname;
    setSelectedKeys([path]);
  }, [location.pathname]);

  // 处理菜单点击
  const handleMenuClick = ({ key }) => {
    navigate(key);
  };

  // 处理退出登录
  const handleLogout = () => {
    localStorage.removeItem('adminUser');
    message.success('退出登录成功');
    navigate('/admin/login');
  };

  // 用户下拉菜单
  const userMenu = {
    items: [
      {
        key: 'profile',
        label: '个人信息',
        icon: <UserOutlined />,
      },
      {
        key: 'logout',
        label: '退出登录',
        icon: <LogoutOutlined />,
        danger: true,
      },
    ],
    onClick: ({ key }) => {
      if (key === 'logout') {
        handleLogout();
      } else if (key === 'profile') {
        navigate('/admin/profile');
      }
    },
  };

  // 检查用户权限
  const hasPermission = (permission) => {
    if (!user || !user.permissions) return false;
    return user.permissions.includes(permission);
  };

  // 根据权限过滤菜单项
  const getAllMenuItems = () => [
    {
      key: '/admin/dashboard',
      icon: <DashboardOutlined />,
      label: '控制台',
      permission: 'dashboard',
    },
    {
      key: '/admin/products',
      icon: <ShoppingOutlined />,
      label: '商品管理',
      permission: 'products',
    },
    {
      key: '/admin/categories',
      icon: <AppstoreOutlined />,
      label: '分类管理',
      permission: 'categories',
    },
    {
      key: '/admin/orders',
      icon: <ShoppingCartOutlined />,
      label: '订单管理',
      permission: 'orders',
    },
    {
      key: '/admin/users',
      icon: <UserOutlined />,
      label: '用户管理',
      permission: 'users',
    },
  ];

  // 根据用户权限过滤菜单项
  const menuItems = getAllMenuItems().filter(item => hasPermission(item.permission));

  if (!user) {
    return null;
  }

  return (
    <Layout className="admin-layout">
      <Sider trigger={null} collapsible collapsed={collapsed} theme="light">
        <div className="admin-logo">
          {collapsed ? '商城' : '商城管理系统'}
        </div>
        <Menu
          mode="inline"
          selectedKeys={selectedKeys}
          onClick={handleMenuClick}
          items={menuItems}
        />
      </Sider>
      <Layout>
        <Header className="admin-header" style={{ background: colorBgContainer }}>
          <Button
            type="text"
            icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
            onClick={() => setCollapsed(!collapsed)}
          />
          <div className="admin-user">
            <Dropdown menu={userMenu}>
              <Space>
                <Avatar icon={<UserOutlined />} src={user.avatar || getUserAvatarPlaceholder(user.username, '64x64')} />
                {user.username}
                <DownOutlined />
              </Space>
            </Dropdown>
          </div>
        </Header>
        <Content
          className="admin-content"
          style={{
            margin: '24px 16px',
            padding: 24,
            background: colorBgContainer,
            borderRadius: borderRadiusLG,
          }}
        >
          <Outlet />
        </Content>
        <Footer className="admin-footer" style={{ textAlign: 'center' }}>
          商城管理系统 ©{new Date().getFullYear()} 版权所有
        </Footer>
      </Layout>
    </Layout>
  );
};

export default AdminLayout; 